package org.inter.fsb.controller;

import org.inter.fsb.controller.BaseController;
import org.inter.fsb.utils.ProxyResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@RestController
@RequestMapping("/inter/upload")
public class UploadController extends BaseController {

    // 设置固定的日期格式
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
    @Value("${uploadUrl}")
    private String basaPath;

    @PostMapping("/fileUp")
    public ProxyResponse uploadFile(HttpServletRequest request,
                                    @RequestParam("file") MultipartFile file) throws IOException {
        //判断如果文件不为空
        if (!file.isEmpty()) {
            //上传文件路径
            String path = basaPath + File.separator;
            Random random = new Random();
            int i = random.nextInt(100000000);
            Date date = new Date();
            String format = sdf.format(date);
            //上传文件名
            String filename = format + i + "-" + file.getOriginalFilename();
            //上传文件类型
            System.out.println("getContentType:" + file.getContentType());
            //上传文件名
            System.out.println("getOriginalFilename:" + file.getOriginalFilename());
            /**
             * 创建一个文件对象，把存文件的路径和文件名放进去
             */
            File filepath = new File(path, filename);
            //路径不存在就创建一个路径
            if (!filepath.getParentFile().exists()) {
                filepath.getParentFile().mkdirs();
            }
            /**
             * 将上传文件保存到一个目标文件中
             */
            file.transferTo(new File(path + filename));
            return toJson(filename);
        }
        return toJson(0);
    }
}















